import { defineStore } from 'pinia'
import { ref } from 'vue'
import { removeToken } from '../composables/auth';
import { getInfo, login } from "../api/manager";
import { useRouter, useRoute } from 'vue-router';
import { setToken } from "@/composables/auth";
import { toast } from '../composables/utils';
export const useInfoStore = defineStore('message-info', () => {
    const router = useRouter();
    const route = useRoute();
    const userInfo = ref({});
    const asideWidth = ref('250px');
    const menus = ref([]);
    const ruleNames = ref([]);
    const routePath = ref(route.fullPath);
    /**记录用户信息 */
    const setUserInfo = (userMsg) => {
        userInfo.value = userMsg;
    };
    /**获取当前登录用户信息 */
    const getUserInfo = () => {
        return new Promise((resolve, reject) => {
            getInfo().then(res => {
                setUserInfo(res);
                getMenusList(res.menus);
                getRuleNames(res.ruleNames);
                resolve(res);
            }).catch(err => reject(err))
        })
    }
    /**登录,存储token */
    const toLogin = ({ username, password }) => {
        return new Promise((resolve, reject) => {
            login({ username, password }).then(res => {
                setToken(res.token);
                resolve();
            }).catch((err) => {
                reject();
            })

        })
    }
    /** 退出登录功能 */
    const logout = () => {
        // 移除token
        removeToken();
        // 2、清除pinia中的个人信息数据
        userInfo.value = {};
        // 3、页面跳转
        router.push('/login');
        // 4、弹出提示框
        toast('退出登录成功', 'success');
    }
    /**折叠菜单功能 */
    const handleMenuWidth = () => {
        asideWidth.value = asideWidth.value === '250px' ? '64px' : '250px';
    };
    /** 获取菜单栏列表 (注：形参与需要被复制的属性名称不应该相同。)*/
    const getMenusList = (menus1) => {
        menus.value = menus1;
    }
    /** 获取权限名称 */
    const getRuleNames = (ruleNames1) => {
        ruleNames.value = ruleNames1;
    }

    return {
        userInfo,
        asideWidth,
        menus,
        ruleNames,
        routePath,
        setUserInfo,
        getUserInfo,
        toLogin,
        logout,
        handleMenuWidth,
    }
}, {
    persist: true
})